<template>
  <div class="container">
    <el-dialog
      :close-on-click-modal="false"
      :title="showTitle"
      :visible="showDialog"
      width="30%"
      @close="closeDialog"
    >
      <el-form
        ref="formsubject"
        :model="form"
        :rules="rules"
      >
        <el-form-item
          label-width="100px"
          label="学科名称"
          prop="subjectName"
        >
          <el-input
            v-model="form.subjectName"
            style="width: 50%"
            placeholder="请输入学科名称"
          />
        </el-form-item>
        <el-form-item
          label-width="100px"
          label="是否显示"
          prop="isFrontDisplay"
        >
          <el-switch
            v-model="form.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value="1"
            inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
        style="text-align: right"
      >
        <el-button @click="closeDialog">取 消</el-button>
        <el-button
          type="primary"
          @click="determine"
        >确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/subjects.js'
export default {
  data () {
    return {
      form: {
        subjectName: '',
        isFrontDisplay: '1' // 是否在页面显示 1是 0否
      },
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' }
        ],
        isFrontDisplay: [{ required: true }]
      }
    }
  },
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    modify: {
      type: Object,
      default: () => {}
    }
  },
  watch: {
    modify (newVal) {
      // console.log(newVal)
      this.form = newVal
      if (newVal.isFrontDisplay === 1) {
        this.form.isFrontDisplay = '1'
      }
    }
  },
  // 计算弹框是否添加还是修改
  computed: {
    showTitle () {
      return this.form.id ? '修改学科' : '新增学科'
    }
  },
  methods: {
    // 关闭弹框
    closeDialog () {
      this.$emit('update:showDialog', false)
      // 清空数据
      this.$refs.formsubject.resetFields()
    },
    // 确定按钮
    determine () {
      this.$refs.formsubject.validate(async (valid) => {
        if (!valid) return
        if (this.form.id) {
          await update(this.form)
          // 提示
          this.$message.success('修改成功')
        } else {
          await add(this.form)
          // console.log(res)
          // 提示
          this.$message.success('新增成功')
        }
        // 重新渲染
        this.$parent.subjectList()
        // 关闭弹框
        this.closeDialog()
      })
    }
  }
}
</script>

<style scoped lang="less"></style>
